package com.itxh.core.excutor;

import com.itxh.core.cache.Cache;
import com.itxh.core.cache.PerpetualCache;
import com.itxh.core.config.BoundSql;
import com.itxh.core.config.Configuration;
import com.itxh.core.config.MappedStatement;

import java.util.List;

// 实现一级缓存处理
public abstract class BaseExecutor implements Executor{

    private Cache cache = new PerpetualCache();
    @Override
    public <T> List<T> query(MappedStatement mappedStatement, Configuration configuration, Object param) {
        BoundSql boundSql = mappedStatement.getSqlSource().getBoundSql(param);

        String key = createKey(boundSql);
        List<Object> list = cache.get(key);

        if(list == null){
            list = queryFromDataBase(mappedStatement,configuration,param);
            cache.put(key,list);
        }

        return (List<T>) list;
    }

    protected abstract <T> List<T> queryFromDataBase(MappedStatement mappedStatement, Configuration configuration, Object param);

    private String createKey(BoundSql boundSql) {
        String sql = boundSql.getSql();
        // select * from user where id = ?
        return sql;
    }
}
